//
//  BlockManager.cpp
//  AvoidBlock
//
//  Created by 함 우식 on 12. 12. 10..
//
//

#include "BlockManager.h"

using namespace cocos2d;

BlockManager::BlockManager()
{
    init();
}

bool BlockManager::init()
{
    const int count = 150;
//    _pBlocks = CCArray::createWithCapacity(count);
 
    _pBlocks = CCArray::create();
    _pBlocks->retain();
    
    for(int i=0;i<30;i++)
    {
        addBlock(0);
        addBlock(1);
        addBlock(2);
        addBlock(3);
        addBlock(4);
    }
    
    _period = 0.1f;
    
    return true;
}

void BlockManager::update(float dt)
{
    _time += dt;
    
    if(_period < _time)
    {
        _time -= _period;
        
        int block_type = 0;
        
        //int probability = arc4random()%100;
		int probability = rand()%100;

        if(probability > 98){
            block_type = 0;
        }else if(probability > 95){
            block_type = 1;
        }else if(probability > 90){
            block_type = 2;
        }else if(probability > 92){
            block_type = 3;
        }else{
            block_type = 4;
        }
        
        appearBlock(block_type);
    }
    
    
    for(int i=0;i<_pBlocks->count();i++)
    {
        Block* block =(Block*)_pBlocks->objectAtIndex(i);
        if(block->isVisible() == false)
        {
            continue;
        }
        
        block->update(dt);
        
        if(block->getPositionY() < -50.0f){
            block->dead();
        }
    }
}

void BlockManager::addBlock(const int type)
{
    Block* block = Block::blockWithType(type);
    
    const float x = (rand()%3200)*0.1f;
    CCPoint origin = ccp(x, 520);
    block->setPosition(origin);
    block->setVisible(false);
    
    this->addChild(block);
    
    _pBlocks->addObject(block);
    
//    block->autorelease();
}

void BlockManager::appearBlock(const int type)
{
    for(int i=0;i<_pBlocks->count();i++)
    {
        Block* block =(Block*)_pBlocks->objectAtIndex(i);
        if(block->isVisible() == true)
        {
            continue;
        }
        
        block->setVisible(true);
        //const float x = (arc4random()%3800) * 0.1f - 20.0f;
		
		const float x = (rand()%3800) * 0.1f - 20.0f;
        CCPoint origin = ccp(x, 520);
        block->_currVelocity = ccp(0.0f, 0.0f);
        block->setPosition(origin);
        return;
    }
}